package com.iot.manager.network;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class WebSocketClient {
    private static final String TAG = "WebSocketClient";
    private static final String WS_URL = "ws://123.56.226.74:3001/ws";
    private final OkHttpClient client;
    private WebSocket webSocket;
    private final WebSocketMessageListener messageListener;
    private String token;

    public interface WebSocketMessageListener {
        void onMessage(String message);
    }

    public WebSocketClient(WebSocketMessageListener listener) {
        this.messageListener = listener;
        this.client = new OkHttpClient();
    }

    public void setToken(String token) {
        this.token = token;
    }

    public void connect() {
        Request request = new Request.Builder()
            .url(WS_URL + (token != null ? "?token=" + token : ""))
            .build();

        webSocket = client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                Log.d(TAG, "WebSocket connected");
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                Log.d(TAG, "Received message: " + text);
                if (messageListener != null) {
                    messageListener.onMessage(text);
                }
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                Log.d(TAG, "Received bytes: " + bytes.hex());
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                Log.d(TAG, "WebSocket closing: " + reason);
                webSocket.close(1000, null);
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                Log.e(TAG, "WebSocket error", t);
            }
        });
    }

    public void disconnect() {
        if (webSocket != null) {
            webSocket.close(1000, "Normal closure");
        }
    }

    public void sendMessage(String message) {
        if (webSocket != null) {
            webSocket.send(message);
        }
    }

    public void sendJson(JsonObject json) {
        if (webSocket != null) {
            webSocket.send(json.toString());
        }
    }
} 